<?php

namespace app\api\controller\v35;


use app\api\controller\v2\Auth;
use app\common\cachemodel\AppSynastryResult;
use app\common\cachemodel\Recode;
use app\common\cachemodel\zl2\Zl2FamousPersonRecode;
use app\common\cachemodel\ZlStarRecode;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\astrolog\SynastryData;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use think\Env;

class Synastry extends Auth
{
    /**
     * 获取合盘结果
     * @throws \Exception
     */
    public function getWithScore()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $rid1 = input('rid1/d', 0);
        $rid2 = input('rid2/d', 0);
        $uid = (int)$this->user['id'];
        $synastryType = 1; //合盘类型 1=>普通合盘 2=>明星合盘 5=>名人合盘

        #神策打点 25 合盘操作 SynastryHandle
        $sensorsTrackData = [
            'synastry_score' => 0,//  合盘得分
            'record1_name' => '',// 合盘左边档案名称
            'record1_id' => $rid1,// 合盘左边档案ID
            'record2_name' => '',// 合盘右边档案名称
            'record2_id' => $rid2,// 合盘右边档案ID
            'has_self' => false,// 是否含有自己的档案
            'is_success' => true,// 是否成功
            'failed_reson' => '',// 失败原因
        ];
        $distinctId = $this->request->header('distinct-id', '');

        if (!in_array($type, [1, 2, 3, 5], true) || ($type === 1 && !$id) || ($type !== 1 && (!$rid1 || !$rid2)))
        {
            if ($distinctId)
            {
                $sensorsTrackData['is_success'] = false;
                $sensorsTrackData['failed_reson'] = '请求参数异常';
                SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
            }
            return show(config('code.error'), '请求异常');
        }

        $recodeModel = new Recode();
        $saveData = [];
        // 通过id查询
        if ($type === 1)
        {
            $result = (new AppSynastryResult())->getInfoById($id);
            if ($result['uid'] != $uid)
            {
                if ($distinctId)
                {
                    $sensorsTrackData['is_success'] = false;
                    $sensorsTrackData['failed_reson'] = '数据不存在';
                    SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
                }
                return show(config('code.error'), '数据不存在');
            }
            if (isset($result['type']))
            {
                $synastryType = (int)$result['type'];
            }

            $records = json_decode($result['extra'], true);
            $rid1 = (int)$result['rid1'];
            $rid2 = (int)$result['rid2'];
            // 获取完整合盘数据
            $records['type'] = 1;

            if (!in_array($synastryType, [5, 6], true) && (!$rid1 || !$rid2))
            {
                $synastryType = 2;
            }
        } else
        {
            $record1 = $recodeModel->getInfoById($rid1, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself', 'sun', 'moon', 'asc']);

            if (!$record1 || $record1['uid'] != $uid)
            {
                return show(config('code.error'), '档案缺失');
            }
            if ($record1['isself'] == 1)
            {
                $record1['name_old'] = $record1['name'];
                $record1['name'] = '自己';
            }

            switch ($type)
            {
                case 3: // 明星合盘
                    $synastryType = 2;// 明星合盘

                    $recodeData = (new ZlStarRecode())->getInfoById($rid2);

                    if (!$recodeData)
                    {
                        return show(config('code.error'), '档案缺失');
                    }

                    $record2 = json_decode($recodeData['extra'], true);
                    break;
                case 5:// 名人合盘
                    $synastryType = 5;// 名人合盘
                    $recodeData = (new Zl2FamousPersonRecode())->getInfoById($rid2);

                    if (!$recodeData)
                    {
                        return show(config('code.error'), '档案缺失');
                    }

                    $record2 = $recodeData['extra'];
                    break;
                default:// 普通合盘
                    $record2 = $recodeModel->getInfoById($rid2, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself']);
                    if (!$record2 || $record2['uid'] != $uid)
                    {
                        if ($distinctId)
                        {
                            $sensorsTrackData['is_success'] = false;
                            $sensorsTrackData['failed_reson'] = '档案不存在或不属于本人';
                            SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
                        }
                        return show(config('code.error'), '档案缺失');
                    }

                    if ($record2['isself'] == 1)
                    {
                        $record2['name'] = '自己';
                    }
            }

            $records = [
                'recode1' => $record1,
                'recode2' => $record2,
                'type' => 1,
            ];

            //rid处理确保入库唯一性
            if ($rid2 > $rid1)
            {
                $newRid1 = $rid2;
                $newRid2 = $rid1;
            } else
            {
                $newRid1 = $rid1;
                $newRid2 = $rid2;
            }

            $saveData = [ // 合盘记录表
                'uid' => $uid,
                'type' => $synastryType,
                'create_type' => 2,
                'rid1' => $newRid1,
                'rid2' => $newRid2,
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
                'nickname1' => $record1['name'],
                'nickname2' => $record2['name'],
                'avatar1' => $record1['avatar'] ?: '',
                'avatar2' => $record2['avatar'] ?: '',
                'extra' => json_encode([
                    'recode1' => $record1,
                    'recode2' => $record2,
                ]),
            ];
        }

        $data = (new SynastryData())->setSynastryType($synastryType)->getScore($records);

        if ($saveData)
        {
            $score = 0;
            foreach ($data['score'] as $item)
            {
                $score += $item['num'];
            }
            $saveData['score'] = $score;// 总分
            $saveData['relation'] = $data['relation'][0]['name_cn']; // 双方可能的关系
            // 去写入
            $id = (new AppSynastryResult())->saveData($saveData, false);
        }

        $data['nickname1'] = $records['recode1']['name'];
        $data['nickname2'] = $records['recode2']['name'];
        $data['avatar1'] = $records['recode1']['avatar'];
        $data['avatar2'] = $records['recode2']['avatar'];
        $data['rid1'] = (int)$rid1;
        $data['rid2'] = (int)$rid2;
        $data['type'] = in_array($synastryType, [1, 5, 6], true) ? $synastryType : 2; // 1显示合盘 2不显示   5=>名人合盘  6=>邀请好友合盘（不添加档案）
        $data['id'] = (int)$id;

        if ((Util::IsHuawei() && Util::CheckAppVersion('2.9.11') !== '小' && !Util::huaweiIsShowAll()) || (Util::AppIsPassShowV1() && Util::CheckAppVersion('2.9.12') === '同'))
        {
            $data['type'] = 2;
        }

        $oss = Env::get('host.photo');
        $btnList[] = [
            'name' => '详细解读',
            'target' => 'local',
            'link' => "synastry_result_explain?id={$id}&need_auth=1",
            'is_new' => 0,
            'icon' => $oss . '/test/synastry/synastry_explain.png',
            'tip_icon' => '',
        ];
        if ($synastryType === 1 && !Util::AppIsPassShowV1())
        {
            // 获取 合盘报告和AI 显隐开关 true=>显示 false=>隐藏
            $synastryReportSwitch = Util::getSynastryReportSwitch();
            if ($synastryReportSwitch)
            {
                if (Util::CheckAppVersion('2.5.2') !== '小')
                {
                    // 获取 当前合盘星盘两个档案是否已经解锁过相关关系
                    $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], $data['rid1'], $data['rid2'], 1);
                    $synastryReportNeedAuth = $this->user['young_model'] ? 3 : 1;
                    $btnList[] = [
                        'name' => '合盘报告',
                        'target' => 'local',
                        'link' => $unlockStatus ? "synastry_report_list?rid1={$records['recode1']['id']}&rid2={$records['recode2']['id']}&srid=1&need_auth={$synastryReportNeedAuth}" : "synastry_report_detail?rid1={$records['recode1']['id']}&rid2={$records['recode2']['id']}&srid=1&need_auth={$synastryReportNeedAuth}",
                        'is_new' => 1,
                        'icon' => $oss . '/test/synastry/synastry_report.png',
                        'tip_icon' => $oss . '/test/synastry/hot_icon.png',
                    ];
                }
                // else
                // {
                //     $btnList[] = [
                //         'name' => '合盘星盘',
                //         'target' => 'local',
                //         'link' => "composite_astro?rid1={$data['rid1']}&rid2={$data['rid2']}&need_auth=1"
                //     ];
                // }
                if (Util::CheckAppVersion('2.10.4') !== '小')
                {
                    $btnList[] = [
                        'name' => 'AI对话解读',
                        'target' => 'local',
                        'link' => "aichat?type=0&rid={$records['recode1']['id']}&rid2={$records['recode2']['id']}&need_auth=0",
                        'icon' => $oss . '/test/synastry/synastry_ai.png',
                        'tip_icon' => '',
                    ];
                }
            }
        }

        $data['btn_list'] = $btnList;

        if ($distinctId)
        {
            if ((!isset($record1) || empty($record1)) && $data['rid1'])
            {
                $record1 = $recodeModel->getInfoById($data['rid1']);
            } elseif (isset($result['rid1']))
            {
                $record1 = $recodeModel->getInfoById($result['rid1']);
            }
            if ((!isset($record2) || empty($record2)) && $data['rid2'])
            {
                $record2 = $recodeModel->getInfoById($data['rid2']);
            } elseif (isset($result['rid1']))
            {
                $record2 = [
                    'id' => $result['rid2'],
                    'name' => $result['nickname2'],
                    'isself' => 0,
                ];
            }
            $totalScore = $data['score']['attract']['num'] +
                $data['score']['chat']['num'] +
                $data['score']['passion']['num'] +
                $data['score']['benefit']['num'] +
                $data['score']['happy']['num'] +
                $data['score']['probTobeLover']['num'];
            $sensorsTrackData['synastry_score'] = $totalScore;
            $sensorsTrackData['record1_name'] = $data['nickname1'];
            $sensorsTrackData['record1_id'] = $data['rid1'];
            $sensorsTrackData['record2_name'] = $data['nickname2'];
            $sensorsTrackData['record2_id'] = $data['rid2'];
            $sensorsTrackData['has_self'] = ((int)$record1['isself'] === 1 || (int)$record2['isself'] === 1);
            SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
        }
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 名人合盘列表
     */
    public function famousPersonSynastryList()
    {
        $id = input('id/d', 0);

        $synastryResultModel = new AppSynastryResult();

        $famousPersonRecodeModel = new Zl2FamousPersonRecode();
        // 获取 名人列表
//        $data = $famousPersonRecodeModel->getListDatas();
        $data = $famousPersonRecodeModel->getInfoData($id);

        // 获取 用户 名人合盘 信息
        $famousPersonSynastryData = $synastryResultModel->getUserFamousPersonList($this->user['id']);

        $recodeHash = null;

        $d1 = [];
        $d2 = [];
        foreach ($data as $datum)
        {
            if (!$recodeHash)
            {
                $recodeInfo = (new Recode())->getInfoById($this->user['rid'], ['type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'ew', 'long_deg', 'long_min', 'ns', 'lat_deg', 'lat_min', 'is_summer']);
                $recodeHash = Util::getRecodeHashKey($recodeInfo);
            }
            if (isset($famousPersonSynastryData[$datum['id']]) && $famousPersonSynastryData[$datum['id']]['hash'] === $recodeHash)
            {
                $datum['btn_info'] = [
                    'title' => "已完成合盘/{$famousPersonSynastryData[$datum['id']]['score']}分",
                    'target' => 'local',
                    'link' => "synastry_result?type=1&id={$famousPersonSynastryData[$datum['id']]['id']}&need_auth=1",
                    'icon' => '/test/synastry/synastry_go.png',
                    'type' => 2,
                ];
            } else
            {
                $datum['btn_info'] = [
                    'title' => '与TA合盘冲击排行榜',
                    'target' => 'local',
                    'link' => "synastry_result?type=5&rid1={$this->user['rid']}&rid2={$datum['id']}&need_auth=1",
                    'icon' => '/test/synastry/synastry_ranking.png',
                    'type' => 1,
                ];
            }

            if ($d2 || (empty($d2) && $datum['id'] === $id))
            {
                $d2[] = $datum;
            } else
            {
                $d1[] = $datum;
            }
        }

        $resData = array_merge($d2, $d1);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 名人合盘排行榜
     */
    public function getFamousPersonSynastryRanking()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $resData = (new AppSynastryResult())->getFamousPersonRankingData($this->user['id'], $id, $this->user['rid']);

        return show(config('code.success'), '请求成功', $resData);
    }
}
